package org.csu.jpetstore_manage_system.web;

import jakarta.servlet.http.HttpServletRequest;
import org.csu.jpetstore_manage_system.domain.Category;
import org.csu.jpetstore_manage_system.domain.Item;
import org.csu.jpetstore_manage_system.domain.Product;
import org.csu.jpetstore_manage_system.persistence.ImageToBase64Code;
import org.csu.jpetstore_manage_system.service.Base64Service;
import org.csu.jpetstore_manage_system.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/categories")
public class CatalogController {

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private Base64Service base64Service;

    @GetMapping
    public ModelAndView getCategoryList(){
        ModelAndView modelAndView = new ModelAndView("page/categories");
        List<Category> categoryList = catalogService.getCategoryList();
        modelAndView.addObject("categoryList", categoryList);
        return modelAndView;
    }


    //增加Category
    @PostMapping
    public ModelAndView addCategory(@RequestParam("catid") String catid,
                                    @RequestParam("name") String name,
                                    @RequestParam("file") MultipartFile file){
        Category category = new Category();
        category.setCatid(catid);
        category.setName(name);
        category.setDescn(base64Service.getBase64(file));

        catalogService.insertCategory(category);
        ModelAndView modelAndView = new ModelAndView("page/categories");
        List<Category> categoryList = catalogService.getCategoryList();
        modelAndView.addObject("categoryList", categoryList);
        return modelAndView;
    }

    @GetMapping("/{categoryId}")
    public ModelAndView getCategory(@PathVariable("categoryId") String categoryId){
        ModelAndView modelAndView = new ModelAndView("page/categoryEdit");
        Category category = catalogService.getCategory(categoryId);

        modelAndView.addObject("category", category);
        return modelAndView;
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    //编辑Category
    @PutMapping("/{categoryId}")
    public ModelAndView updateCategory(@PathVariable String categoryId,
                                       @RequestParam String name,
                                       @RequestParam(value = "file") MultipartFile file){
        Category category = catalogService.getCategory(categoryId);
        category.setName(name);
        category.setDescn(base64Service.getBase64(file));

        catalogService.updateCategory(category);

        ModelAndView modelAndView = new ModelAndView("page/categories");
        List<Category> categoryList = catalogService.getCategoryList();
        modelAndView.addObject("categoryList", categoryList);
        return modelAndView;
    }

    //删除Category，包括Category下的所有product，product下的所有item
    @GetMapping("/delete/{categoryId}")
    public ModelAndView deleteCategory(@PathVariable("categoryId") String categoryId){
        catalogService.deleteCategory(categoryId);

        return getCategoryList();
    }

    @GetMapping("/search")
    public ModelAndView searchCategory(@RequestParam("keyword") String keyword) {
        ModelAndView modelAndView = new ModelAndView("page/categories");
        if (keyword.isEmpty())
            return getCategoryList();
        else{
            List<Category> categoryList = catalogService.getCategoryByKeyWord(keyword);
            modelAndView.addObject("categoryList", categoryList);
            return modelAndView;
        }
    }


    //查看product
    @GetMapping("/{categoryId}/products")
    public String getProductList(
            @PathVariable("categoryId") String categoryId,
            Model model){
        List<Product> productList =  catalogService.getProductListByCategory(categoryId);
        model.addAttribute("productList", productList);
        model.addAttribute("categoryId", categoryId);
        return "page/products";
    }

    //搜索product
    @GetMapping("/{categoryId}/products/search")
    public String searchProduct(@RequestParam("keyword") String keyword, Model model, @PathVariable String categoryId){
        List<Product> productList = catalogService.searchProductList(keyword);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("productList", productList);
        return "page/products";
    }

    //增加product
    @PostMapping("/{categoryId}/products")
    public String addProduct(@PathVariable String categoryId,
                             @RequestParam("id") String productId,
                             @RequestParam("name") String name,
                             @RequestParam("file") MultipartFile file,
                             Model model){
        Product product = new Product();
        product.setProductId(productId);
        product.setName(name);
        product.setDescn(base64Service.getBase64(file));
        product.setCategory(categoryId);

        catalogService.insertProduct(product);
        List<Product> productList =  catalogService.getProductListByCategory(categoryId);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("productList", productList);
        return "page/products";
    }

    //打开编辑product页面
    @GetMapping("/{categoryId}/products/{productId}")
    public String getProduct(@PathVariable("categoryId") String categoryId,
                                @PathVariable("productId") String productId,
                                Model model){
       Product product = catalogService.getProduct(productId);
       model.addAttribute("categoryId", categoryId);
       model.addAttribute("productId", productId);
       model.addAttribute("product", product);
        return "page/productEdit";
    }
    //编辑product
    @PutMapping("/{categoryId}/products/{productId}")
    public String updateProduct(@PathVariable("categoryId") String categoryId,
                                @PathVariable("productId") String productId,
                                @RequestParam("name") String name,
                                @PathVariable("file") MultipartFile file,
                                Model model){
        Product product = new Product();
        product.setProductId(productId);
        product.setName(name);
        product.setCategory(categoryId);
        product.setDescn(base64Service.getBase64(file));

        catalogService.updateProduct(product);
        List<Product> productList =  catalogService.getProductListByCategory(categoryId);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("productList", productList);
        return "page/products";
    }

    //删除product
    @DeleteMapping("/{categoryId}/products/delete/{productId}")
    public String deletProduct(@PathVariable String categoryId,
                               @RequestParam("productId") String productId,
                               Model model) {
        catalogService.deleteProduct(productId);
        List<Product> productList =  catalogService.getProductListByCategory(categoryId);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("productList", productList);
        return "page/products";
    }


    @GetMapping("/{categoryId}/products/{productId}/items")
    public String getItemList(@PathVariable String categoryId,
                              @PathVariable("productId") String productId,
                              Model model ){
        List<Item> itemList = catalogService.getItemListByProduct(productId);
        model.addAttribute("itemList", itemList);
        return "page/items";
    }

    @GetMapping("/{categoryId}/products/{productId}/addItem")
    public ModelAndView addItemView(@PathVariable String productId){
        ModelAndView modelAndView = new ModelAndView("page/table/itemAdd");
        modelAndView.addObject("productId",productId);
        return modelAndView;
    }

    @PostMapping("/{categoryId}/products/{productId}/addItem")
    @ResponseBody
    public String addItem(@RequestBody Item item,Model model){
        boolean result = catalogService.insertItem(item);
        model.addAttribute("result",result);
        return "添加完成！";
    }

    @GetMapping("/{categoryId}/products/{productId}/items/{itemId}")
    public ModelAndView editItem(@PathVariable String itemId){
        ModelAndView modelAndView = new ModelAndView("page/itemEdit");
        Item item = catalogService.getItem(itemId);
        modelAndView.addObject("item",item);
        return modelAndView;
    }

    @PostMapping("/{categoryId}/products/{productId}/items/{itemId}")
    @ResponseBody
    public String editItem(@RequestBody Item item,@PathVariable String itemId){
        Item item1 = catalogService.getItem(itemId);
        System.out.println(item1);
        item1.setAttr1(item.getAttr1());
        item1.setItemId(itemId);
        item1.setListPrice(item.getListPrice());
        item1.setQuantity(item.getQuantity());
        item1.setUnitCost(item.getUnitCost());
        boolean result = catalogService.updateItem(item1);
        System.out.println(result);
        return String.valueOf(result);
    }

    @GetMapping ("{categoryId}/products/{productId}/deleteItems/{itemId}")
    public ModelAndView deleteItem(@PathVariable String itemId,@PathVariable String productId){
        ModelAndView modelAndView = new ModelAndView("page/items");
        boolean result = catalogService.deleteItem(itemId);
        List<Item> itemList = catalogService.getItemListByProduct(productId);
        modelAndView.addObject("itemList",itemList);
        return modelAndView;
    }

    @GetMapping("{categoryId}/products/{productId}/updateState/{itemId}")
    public String updateState(Model model,@RequestParam("itemState") String state,@PathVariable String itemId,@PathVariable String productId){
        Item item = catalogService.getItem(itemId);
        System.out.println(state);
        item.setStatus(state);
        catalogService.updateItem(item);
        List<Item> itemList = catalogService.getItemListByProduct(productId);
        model.addAttribute("itemList",itemList);
        return "page/items";
    }

    @GetMapping("{categoryId}/products/{productId}/searchItem")
    public String searchItem(Model model,@RequestParam("itemId") String itemId){
        Item item = catalogService.getItem(itemId);
        model.addAttribute("item",item);
        return "page/itemEdit";
    }
}
